import store from "@/store";
import axios from "axios";

const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});
// 请求之前
instance.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("x-auth-token");
    // 统一携带token
    if (token) {
      config.headers["x-auth-token"] = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 获得数据之前
instance.interceptors.response.use(
  (res) => {
    let response = res.data;
    if (res.data.code != 0 && res.data.code != 400 && res.data.code != 407) {
      // 没有登录返回false
      if (res.data.code == 401) return false;
      store.dispatch("showToast/asyncChangeStatus", {
        content: response.message,
        type: "danger",
      });
      return false;
    }
    return res.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);
export default instance;
